
#!/bin/bash
#author: xlp
#Version: v0.1

listforcom=$1

if [ $# -ne 1  ]
then
	echo "usage[ xstackimg.sh listcom  ]"
	exit 0
fi

if test -r reducxy
then
	rm -rf reducxy
fi

mkdir reducxy
cp $listforcom reducxy
for fitfile in `cat $listforcom`
do
	cp $fitfile reducxy
done
cd reducxy
cp ~/software/softgft_mainFocus/* ./

Dir_otcheck=`pwd`

rm -rf ref.fit
rm -rf *sub.fit *lin.fit bak*.fit ker*.fit  *psf.fit
rm -rf flag.log *2sd.fit *phot.fit
rm -rf *sub.jpg 
rm -rf listcombine 


Nobj_c=3  # the min num for the object in the sub new image 
fwhm_min=1.17

rdnoise=3
gain=1

cd $Dir_otcheck
echo $Dir_otcheck
cp -r ~/software/newxgwacmatchsoft/* $Dir_otcheck
cp $listforcom $Dir_otcheck
cp $listforcom listcom_as

xdefineDir ( )
{
stringtimeForMonitorT=`date -u +%Y%m%d`
Dir_monitor_allplot=`echo $Dir_otcheck"/"$stringtimeForMonitorT`
if test ! -r $Dir_monitor_allplot 
then
    mkdir $Dir_monitor_allplot
fi
fitscutpngmonitor=`echo $Dir_monitor_allplot"/otcheck_"$stringtimeForMonitorT".1.log"`
OTCandidateslist=`echo $Dir_monitor_allplot"/OTCandidateslist.1.log"`

if test ! -r $HOME/iraf
then
    echo "no iraf file with the name of iraf"
    exit        
fi
}


xmatchTwoImage (  )
{
	echo "xmatchTwoImage" >>$fitscutpngmonitor
    echo "xmatchTwoImage"
    #matchflag=tolerance
    matchflag=triangle
    fitorder=3
     OUTPUT_new=$NewOTimageStarList_xy
     tempmatchstars=ref.xy
     toleranceredius=100
      
     xNpixel=`gethead $NewOTimage "NAXIS1" | awk '{print($1)}' `
    yNpixel=`gethead $NewOTimage "NAXIS1" | awk '{print($1)}'`
   
    echo $xNpixel $yNpixel
    echo "fit order is: $fitorder"
    
    echo `date` "First tolerance match"
    if test -r $NewOTimage
	then
	echo "have  $NewOTimage "
	else
	echo "no $NewOTimage" 
	fi
     rm -rf $tran2
  
	echo "======xyxymatch==="
    cd $HOME/iraf
    cp -f login.cl.old login.cl
    echo noao >> login.cl
    echo image >> login.cl
    echo immatch >> login.cl
    echo "cd $Dir_otcheck" >> login.cl
    wc $OUTPUT_new
    wc $tempmatchstars
    head -1 $OUTPUT_new
    head -1 $tempmatchstars
    rm -rf $imagetmp1sd $imagetrans1sd $tran2
   echo "xyxymatch(\"$OUTPUT_new\",\"$tempmatchstars\", \"$imagetmp1sd\",toleranc=$toleranceredius, xcolumn=1,ycolumn=2,xrcolum=1,yrcolum=2,separation=7, matchin=\"$matchflag\", inter-,verbo-) " >>login.cl
   echo "geomap(\"$imagetmp1sd\", \"$imagetrans1sd\", transfo=\"$inprefix\", verbos-, xmin=1, xmax=$xNpixel, ymin=1, ymax=$yNpixel,         fitgeom=\"general\", functio=\"legendre\",xxorder=$fitorder,xyorder=$fitorder,xxterms=\"half\",yxorder=$fitorder,yyorder=$fitorder,          yxterms=\"half\", maxiter=5,reject=2.5,inter-)" >>login.cl
    echo "geotran(\"$NewOTimage\", \"$tran2\", \"$imagetrans1sd\", \"$inprefix\",interpolant=\"linear\", nxblock=4096, nyblock=4096)" >>login.cl
    echo logout >> login.cl
    cl < login.cl
    #cl < login.cl >xlogfile
    cd $HOME/iraf
    cp -f login.cl.old login.cl
    cd $Dir_otcheck
    echo  "xyxymatch and geomap are over"
    if test -r $tran2
    then
    	echo  $tran2 >>listcombine
	cp $tran2 ../
    	echo "@@@@@@@@@@"
    else
	echo "No $tran2 exit!"
    fi
    cat $imagetrans1sd | grep rms
}

xcombine ( )
{

    echo "xcombine"
    if test -s listcombine
    then
	    echo "have listcombine"
	    cat listcombine
    else
	    echo "no listcombine"
	    exit 0
    fi
if test -r $comimage
then
	rm -rf $comimage
fi
cd $HOME/iraf
cp -f login.cl.old login.cl
echo noao >> login.cl
echo digiphot >> login.cl
echo daophot >>login.cl
echo "cd $Dir_otcheck" >> login.cl
echo flpr >> login.cl
echo "imcombine(\"@listcombine\",\"$comimage\", reject=\"crreject\",combine=\"median\",scale=\"exposure\",weight=\"exposure\",rdnoise=$rdnoise,gain=$gain)" >>login.cl
echo logout >>login.cl
cl < login.cl
#cl < login.cl >xlogfile
cd $HOME/iraf
cp -f login.cl.old login.cl
#----------------------------------------------
cd $Dir_otcheck
ls $comimage
newwcsfitnew=`echo $comimage | sed 's/.fit/.new/g'`
xastro_cgft.sh $comimage
wait
ls $comimage
if test -s $newwcsfitnew
then
	cp $newwcsfitnew $comimage
fi
rm -rf listcombine listcom listcom_as
mv $comimage ../
cd ../
rm -rf reducxy
}


xotcheckdefine (  )
{
    inprefix=`echo $NewOTimage | cut -c1-14`
    inprefixfit=`echo $inprefix | awk '{print($1"*.fit")}'`
    inprefixallfile=`echo $inprefix | awk '{print($1"*")}'`
    #inprefixallfile=`echo $NewOTimage | sed 's/.fit/*/'`
    NewOTimagebg=`echo $NewOTimage | sed 's/.fit/_bg.fit/'`
    NewOTimagesubbg=`echo $NewOTimage | sed 's/.fit/_subbg.fit/'`
    photometry_comp=`echo $NewOTimage | sed 's/.fit/_phot.fit/'`
    photometry_compStarList=`echo $NewOTimage | sed 's/.fit/_phot.cat/'`
    refimagebg=`echo $refimage | sed 's/.fit/_bg.fit/'`
    refimagesubbg=`echo $refimage | sed 's/.fit/_subbg.fit/'`
    #refimageStarList_fwhm=`echo $refimage | sed 's/.fit/_fwhm.cat/'`
    NewOTimageStarList_fwhm=`echo $NewOTimage | sed 's/.fit/_fwhm.cat/'` 
    NewOTimageStarList_xy=`echo $NewOTimage | sed 's/.fit/.xy/'`
    NewOTimage_1=`echo $NewOTimage | awk '{print($1"[1]")}'`
    NewOTimageStarList=`echo $NewOTimage | sed 's/.fit/.cat/'`
    #Newimageimstat=`echo $NewOTimage_1 | awk '{print($1"[40:60,40:60]")}'`
    Newimageimstat=`echo $NewOTimage | awk '{print($1"[40:60,40:60]")}'`

    resfile=`echo $inprefix | awk '{print($1".imstat")}'`
    imagetmp1sd=`echo $NewOTimage | sed 's/.fit/.mattmp1sd/'`
    imagetrans1sd=`echo $NewOTimage | sed 's/.fit/.trans1sd/'`
    tran2=`echo $NewOTimage | sed 's/.fit/_2sd.fit/'`
    fluxcorr=`echo $NewOTimage | sed 's/.fit/_fluxcorr.fit/'`
    #inprefix=`echo $NewOTimage | sed 's/.fit//'`
    subimage=`echo $NewOTimage | sed 's/.fit/_sub.fit/'`
    subimageStarList=`echo $NewOTimage | sed 's/.fit/_sub.cat/'`
    ccdimgjpg=`echo $subimage | sed 's/\.fit/\.jpg/'`
    psfmatchimage=`echo $NewOTimage | sed 's/.fit/_psfmatch.fit/'`
    linmatchimage=`echo $NewOTimage | sed 's/.fit/_linmatch.fit/'`
    OTconfirmlst=`echo $NewOTimage | sed  's/.fit/_otconfirmlst.cat/'`
    OTconfirmlstnew=`echo $NewOTimage | sed  's/.fit/_otconfirmlst_new.cat/'`
    OTconfirmlstTmp=`echo $NewOTimage | sed  's/.fit/_otconfirmlst_tmp.cat/'`
    OTconfirmlstRef=`echo $NewOTimage | sed  's/.fit/_otconfirmlst_ref.cat/'`
    OTconfirmlstRef_crosstalk=`echo $NewOTimage | sed  's/.fit/_otconfirmlst_ref_crosstalk.cat/'`
    
    OTconfirmlstPsf=`echo $NewOTimage | sed  's/.fit/_otconfirmlst_psf.cat/'`
    
}


xmkmovie ( )
{
    gifname=subfitmovie.gif
    convert -delay 10 *sub.jpg -loop 0 $gifname
}



xfit2jpg ( )
{
    xim=50
    yim=50
    subridus=50

    if test -r $subimage
    then
        jpgimg=`echo $subimage | sed 's/\.fit/.jpg/g'`
        python fits_cut_to_png_galaxy.py $subimage $jpgimg $xim $yim $subridus \" \"
    fi

}

xcheckrefimage_new ( )
{

echo "=======check the ref.fit =========="



if test -r ref.xy
    then
        echo "OK"

    else
        echo "no ref.fit"
	if test ! -s listcom_as
	then
		echo "no listcom_as"
		break
	fi
	cat listcom_as
        newlastimage=`head -1 listcom_as | awk '{print($1)}'`
        refimage=`echo $newlastimage | sed 's/.fit/_ref.fit/g'`
        echo $newlastimage $refimage
        cp $newlastimage $refimage 


        refimageStarList=`echo $refimage | sed 's/.fit/.cat/g'`
        refimageStarList_fwhm=`echo $refimage | sed 's/.fit/.fwhm/g'`
        comimage=`echo $newlastimage | sed 's/.fit/_c.fit/g'`
        cp $refimage ref.fit
        echo $refimage
        sex $refimage -c daofind.sex -DETECT_THRESH 50 -ANALYSIS_THRESH 50
        mv image.sex $refimageStarList
        #cat $refimageStarList 
        echo $refimageStarList
        echo $refimage
     #   cat $refimageStarList | awk '{if($4==0)print($0)}' | sort -n -k 8 | head -4  >$refimageStarList_fwhm
#        cat $refimageStarList | awk '{if($4==0 && ($10/$3)<0.5)print($0)}' | sort -n -k 8 | awk '{print($1,$2)}' >ref.xy
	cat $refimageStarList | awk '{if($8==0)print($0)}' | sort -n -k 4 | awk '{print($1,$2)}' | head -50 >ref.xy
	head -1 ref.xy
        #cat ref.xy
        #xy2sky -d $newlastimage @ref.xy  | awk '{print($1,$2)}'>ref.radec
        #cat ref.radec
        echo "============="
    fi
}

xcheckNewimage_new ( )
{
for NewOTimage in `cat listcom_as`
do
    echo $NewOTimage 
    xotcheckdefine
    sex $NewOTimage -c daofind.sex -DETECT_THRESH 50 -ANALYSIS_THRESH 50
    cat image.sex  | awk '{if($8==0)print($0)}' | sort -n -k 4 | awk '{print($1,$2)}' | head -30>$NewOTimageStarList_xy 

    xmatchTwoImage
    echo "For $NewOTimage, the process is over"
    echo "============"
done
}


xastronomy ( )
{
    echo "xastronomy"
    rm -rf listcom_as
    for fitfileas in `cat $listforcom`
    do
        echo $fitfileas
	gethead $fitfileas "CRVAL1" >crval1.log
	if test  -s crval1.log
	then
		echo "Astronomy is finished"
		ls $fitfileas >>listcom_as
	else
        	newfitfileas=`echo $fitfileas | sed 's/.fit/.new/g'`
		solve-field -O -p  --use-sextractor -scale -H 1.75 -L 1.70 -u app  $fitfileas -l 300
       		wait
       		if test -r $newfitfileas
       		then
       		    echo "$fitfileas astronomy calibrated to $newfitfileas "
       		    cp $newfitfileas $fitfileas 
       		    ls $fitfileas >>listcom_as
       		fi
	fi

    done
   cat listcom_as

}

xflatcheckandcombine (  )
{
    dir_now=`pwd`
    dirFlat="/disk2/test/xlp2/svom/caliFile/Flat"
    #dirFlatg="/disk2/test/xlp2/svom/caliFile/Flat_g.fit"
    #dirFlati="/disk2/test/xlp2/svom/caliFile/Flat_i.fit"
    dirZero="/disk2/test/xlp2/svom/caliFile/Zero.fit"
    filter=`gethead $fitname "filter"`
    flatnamedir=`echo $dirFlat"_"$filter".fit"`
    if [ -r $flatnamedir ] && [ -r $dirZero  ]
    then
            cp $flatnamedir $dirZero ./
            flatname=`echo "Flat_"$filter".fit"`
            xzeroflatcorr.sh $fitname $flatname
    fi
}


#while : 
#do
#    xastronomy
    xdefineDir
    xflatcheckandcombine
    xcheckrefimage_new
    xcheckNewimage_new
    xcombine
#done


